from pylab import *
from xml.dom.minidom import parseString
from urllib import *

loc_cache = {}

class matchrow:
	def __init__(self, row, allnum=False):
		if allnum:
			self.data = map(float, row[0:len(row)-1])
		else:
			self.data = row[0: len(row) - 1]

		self.match = int(row[len(row) - 1])
	
#load data
def loadmatch(f, allnum=False):
	rows = []
	for line in file(f):
		rows.append(matchrow(line.strip().split(','), allnum=allnum))

	return rows

def loadnumerical():
	oldrows = loadmatch('./data/matchmaker.csv')
	newrows = []
	for row in oldrows:
		d = row.data
		data = [float(d[0]), yesno(d[1]), yesno(d[2]),
			float(d[5]), yesno(d[6]), yesno(d[7]),
			matchcount(d[3], d[8]), milesdistance(d[4], d[9]), row.match]
		newrows.append(matchrow(data, allnum = True))

	return newrows

#test data
def plotagematches(rows):
	xdm, ydm = [r.data[0] for r in rows if r.match == 1], [r.data[1] for r in rows if r.match == 1]
	xdn, ydn = [r.data[0] for r in rows if r.match == 0], [r.data[1] for r in rows if r.match == 0]

	print xdm
	plot(xdm, ydm, 'go')
	plot(xdn, ydn, 'ro')

	savefig('ana.png')
	show()

#averge point 
def lineartrain(rows):
	averages = {}
	counts   = {}

	for row in rows:
		cl = row.match
		
		averages.setdefault(cl, [0.0] * len(row.data))
		counts.setdefault(cl, 0)

		for i in range(len(row.data)):
			averages[cl][i] += float(row.data[i])

		counts[cl] += 1

	for cl, avg in averages.items():
		for i in range(len(avg)):
			avg[i] /=  counts[cl]

	return averages

def yesno(v):
	"""
		1: yes, -1: no, 0: not clear
	"""
	if v == 'yes': return 1
	elif v == 'no': return -1
	return 0


def getlocation(location):
	appid = 'OQMGQmjV34HUAweHpMTkJ6ojlfxuGwAl2d.FN2F.yRCnT8i_wqeDWm44h6GWGo.eIVWffw_1pZ2zz37T'
	service_domain = 'http://local.yahooapis.com/MapsService/V1/geocode?'
	service_url = service_domain + 'appid=%s' %appid + '&location=%s' %quote_plus(location)

	if location in loc_cache:
		return loc_cache[location]

	data = urlopen(service_url).read()
	doc = parseString(data)

	lat = float(doc.getElementsByTagName('Latitude')[0].firstChild.nodeValue)
	long = float(doc.getElementsByTagName('Longitude')[0].firstChild.nodeValue)

	loc_cache[location] = (lat, long)
	return (lat, long)


def milesdistance(a1, a2):
	lat1, long1 = getlocation(a1)
	lat2, long2 = getlocation(a2)

	latdif = 69.1 * (lat1 - lat2)
	longdif = 53 * (long1 - long2)
	
	return (latdif ** 2 + longdif ** 2) ** .5


def matchcount(interest1, interest2):
	i1 = interest1.split(':')
	i2 = interest2.split(':')

	x = 0
	for item in i1:
		if item in i2:
			x += 1
	return x

def scaledata(rows):
	low = [999999999999999.0] * len(rows)
        high = [-999999999999999.0] * len(rows)

	for row in rows:
		for i in range(len(row.data)):
			if row.data[i]  < low[i]:  low[i] = row.data[i]
			if high.data[i] > high[i]: high[i] = row.data[i]

	def scaleinput(d):
		return [d.]
			




#dotproduct
def dotproduct(v1, v2):
	return sum([(v1[i] * v2[i]) for i in range(len(v1))])


def dpclassify(point, avgs):
	b = (dotproduct(avgs[1], avgs[1]) - dotproduct(avgs[0], avgs[0])) / 2
	y = (dotproduct(point, avgs[1]) - dotproduct(point, avgs[0])) - b
	if y < 0: return 0
	else: return 1

		

		
